import React, { Fragment } from 'react'
import store from '../store'


class Todolist extends React.Component {
    constructor() {
        super()
        this.state = store.getState()
        store.subscribe(this.storeChange)
    }

    change() {
        let action = {
            type: 'change_input_value',
            value: this.input.value
        }
        store.dispatch(action)
    }
    add() {
        let action = {
            type: 'add_todo_item'
        }
        store.dispatch(action)
        store.getState()
    }

    delete(index) {
        let action = {
            type: 'remove_item',
            index
        }
        store.dispatch(action)
    }
    handleKeydown(e) {
        if (e.keyCode === 13) {
            this.add();
        }
    }

    storeChange = () => {
        this.setState(store.getState())
    }

    render() {
        return (
            <Fragment>
                <input className="form-control"
                    style={{ "width": "200px", "display": "inline" }}
                    type="text"
                    value={this.state.inputValue}
                    onChange={this.change.bind(this)}
                    onKeyDown={this.handleKeydown.bind(this)}
                    ref={(input) => this.input = input}
                />
                <input type="button" onClick={this.add.bind(this)}
                    className="btn btn-info" value="提交" />
                <ol>
                    {
                        this.state.list.map((item, index) => {
                            return <li title="点击删除" onClick={this.delete.bind(this, index)}
                                key={index}>{item}</li>
                        })
                    }
                </ol>
            </Fragment>
        )
    }

    componentDidMount() {
        console.log("componentDidMount：组件被挂载到页面之后自动执行")
    }
}

export default Todolist